<template>
  <div class="user-manage-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统中的所有用户信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input
            v-model="searchForm.userAccount"
            placeholder="请输入用户账号"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户列表 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userName" label="用户名" min-width="120" />
        <el-table-column prop="userAccount" label="用户账号" min-width="120" />
        <el-table-column prop="userAvatar" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar
              v-if="row.userAvatar"
              :src="row.userAvatar"
              :size="40"
            />
            <el-avatar v-else :size="40" :icon="UserFilled" />
          </template>
        </el-table-column>
        <el-table-column prop="userProfile" label="用户简介" min-width="150" show-overflow-tooltip />
        <el-table-column prop="userRole" label="用户角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.userRole === 'admin' ? 'danger' : 'primary'">
              {{ row.userRole === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.id ? '编辑用户' : '新增用户'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户账号" prop="userAccount">
          <el-input
            v-model="editForm.userAccount"
            placeholder="请输入用户账号"
            :disabled="!!editForm.id"
          />
        </el-form-item>
        <el-form-item label="用户简介" prop="userProfile">
          <el-input
            v-model="editForm.userProfile"
            type="textarea"
            :rows="3"
            placeholder="请输入用户简介"
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="userRole">
          <el-select v-model="editForm.userRole" placeholder="请选择用户角色">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh, Edit, Delete, UserFilled } from '@element-plus/icons-vue'
import { list, update } from '@/api/userController'

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 用户列表
const userList = ref<API.User[]>([])
const selectedUsers = ref<API.User[]>([])

// 搜索表单
const searchForm = reactive({
  userName: '',
  userAccount: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 编辑对话框
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive({
  id: undefined as number | undefined,
  userName: '',
  userAccount: '',
  userProfile: '',
  userRole: 'user'
})

// 编辑表单验证规则
const editRules: FormRules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应为2-20位', trigger: 'blur' }
  ],
  userAccount: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 4, max: 16, message: '账号长度应为4-16位', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true

    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      userName: searchForm.userName || undefined,
      userAccount: searchForm.userAccount || undefined
    }

    const res = await list(params)

    if (res.data.code === 0 && res.data.data) {
      userList.value = res.data.data || []
      pagination.total = res.data.data.length || 0
    } else {
      ElMessage.error(res.data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.userName = ''
  searchForm.userAccount = ''
  pagination.current = 1
  fetchUserList()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.current = 1
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchUserList()
}

// 选择改变
const handleSelectionChange = (selection: API.User[]) => {
  selectedUsers.value = selection
}

// 编辑用户
const handleEdit = (row: API.User) => {
  editForm.id = row.id
  editForm.userName = row.userName || ''
  editForm.userAccount = row.userAccount || ''
  editForm.userProfile = row.userProfile || ''
  editForm.userRole = row.userRole || 'user'
  editDialogVisible.value = true
}

// 删除用户
const handleDelete = async (row: API.User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.userName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await update({ id: row.id })

    if (res.data.code === 0) {
      ElMessage.success('删除成功')
      fetchUserList()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 保存用户
const handleSave = async () => {
  if (!editFormRef.value) return

  try {
    await editFormRef.value.validate()

    saveLoading.value = true

    const res = await update(editForm)

    if (res.data.code === 0) {
      ElMessage.success('保存成功')
      editDialogVisible.value = false
      fetchUserList()
    } else {
      ElMessage.error(res.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存失败，请检查网络连接')
  } finally {
    saveLoading.value = false
  }
}

// 对话框关闭
const handleDialogClose = () => {
  editFormRef.value?.resetFields()
  editForm.id = undefined
  editForm.userName = ''
  editForm.userAccount = ''
  editForm.userProfile = ''
  editForm.userRole = 'user'
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-manage-container {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

.search-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.table-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-manage-container {
    padding: 16px;
  }

  .page-header,
  .search-section,
  .table-section {
    padding: 16px;
  }

  .search-form {
    display: block;
  }

  .search-form .el-form-item {
    margin-bottom: 16px;
    display: block;
  }
}
</style>
